import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
//引入element 图标资源
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from "element-plus";
//修改elementPlus默认为中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

//配置访问后端的根路径为全局变量
const BASE_URL = 'http://localhost:8080';
//通过window里面添加BASE_URL为全局变量，可以任意的script中使用
window.BASE_URL = BASE_URL
//element图标资源需要循环遍历，放入到app中
//先把使用的app单独定义出来
const app = createApp(App)
//在vue中也要添加BASE_URL为全局变量，这样可以在<template>使用
app.config.globalProperties.BASE_URL = BASE_URL;
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
//开启跨域携带cookie
window.axios = axios;
axios.defaults.withCredentials = true
//替换全局axios
app.config.globalProperties.$axios = axios

//axios拦截器设置(响应内容)，根据Security状态码是 401 403
axios.interceptors.response.use(
    response => response,
    error => {
        //控制台打印异常
        console.log(error);
        ElMessage.error(error.response.data.msg);
        //判断授权失败，然后清空localStorage中用户信息和面包屑，结合index.js中的代码进行跳转
        if(error.response.status==401 || error.response.status==403){
            localStorage.removeItem('user'); //清空localStorage中用户信息
            localStorage.removeItem('breadcrumb'); //清空localStorage中面包屑
            window.location.reload(); //重新加载
        }else if(error.response.data.path.indexOf('login')!=-1 && error.response.status==404){
            //判断当前页面是否为登录页面，并且404(资源不存在)
            window.location.reload();
        }
    }
)

app.use(ElementPlus,{locale: zhCn}).use(store).use(router).mount('#app')

//定义获取用户信息的方法
window.getUser = ()=>{
    return localStorage.user?JSON.parse(localStorage.user):null
}

const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
//覆盖
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}
